import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        title: 'Material App',
        home: HYHomePage()
    );
  }
}

class HYHomePage extends StatefulWidget {
  @override
  _HYHomePageState createState() => _HYHomePageState();
}

class _HYHomePageState extends State<HYHomePage> {
  int data = 100;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("InheritedWidget"),
      ),
      body: CounterWidget(
        counter: data,
        child: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              HYShowData()
            ],
          ),
        ),
      ),
      floatingActionButton: FloatingActionButton(
        child: Icon(Icons.add),
        onPressed: () {
          setState(() {
            data++;
          });
        },
      ),
    );
  }
}

class HYShowData extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    int data = CounterWidget.of(context).counter;
    return Text("当前数字：$data",style: TextStyle(fontSize: 30),);
  }
}


class CounterWidget extends InheritedWidget {
//  1.共享数据
  final int counter;
//  2.定义构造方法
  CounterWidget({this.counter,Widget child}): super(child: child);
//  3.获取组件最近的当前InheritedWidget
  static CounterWidget of(BuildContext context){
//  沿着Element树，去找到最近的CounterElement，Element中取出Widget对象
    return context.dependOnInheritedWidgetOfExactType();
  }
//  4.决定要不要回调State中的didChangeDependencies
//  updateShouldNotify方法是对比新旧HYDataWidget，是否需要对更新相关依赖的Widget
//  如果返回为true：执行依赖当前的InheritedWidget的state中didChangeDependencies方法
  bool updateShouldNotify(CounterWidget oldWidget) {
    return this.counter != oldWidget.counter;
  }
}
